<template>
  <div style="background-color: #f3f6fd;height: 100vh">
    <div class="chat-header">
      <img src="@/assets/images/tx.png" alt="" style="width: 50px; height: 50px"/>
      <div style="margin-left: 10px">{{robotDetail.bot_name}}</div>
    </div>
    <div :style="{paddingLeft:screenWidth>500 ? '20%':'0',paddingRight:screenWidth>500 ? '20%':'0'}">
      <!-- 聊天记录区域 -->
      <div style="flex: 1 1 auto;padding: 12px 16px;
                overflow-y: auto;
                width: 100%;
                height: 76vh;
                scrollbar-width: none;
                -ms-overflow-style: none;
              ">
        <div
          v-for="(msg, idx) in chatHistory"
          :key="idx"
          :style="{display: 'flex',marginBottom: '24px',justifyContent:msg.role === 'user' ? 'flex-start' : 'flex-start',}">
          <!-- 机器人头像 / 用户头像 -->
          <img
            v-if="msg.role === 'bot'"
            src="@/assets/images/tx.png"
            style="width: 40px;height: 40px;border-radius: 50%;margin-right: 8px;"/>
          <img
            v-else
            src="@/assets/images/yh.png"
            style="width: 40px;height: 40px;border-radius: 50%;margin-right: 8px;"/>
          <div
            v-if="msg.role == 'user'"
            :style="{
                    maxWidth: '100%',
                    padding: '8px 12px',
                    borderRadius: '12px',
                    backgroundColor:'#7363e9',
                    color: '#fff',
                    boxShadow: '0 1px 3px rgba(0,0,0,.1)',
                    wordBreak: 'break-word', // 自动换行
                    overflowWrap: 'break-word',
                    fontSize:'20px'
                  }"
          >
            <div>{{ msg.content }}</div>
          </div>
          <div
            v-if="msg.role == 'bot'"
            :style="{
                    maxWidth: '100%',
                    padding: '8px 12px',
                    borderRadius: '12px',
                    backgroundColor:'#fafafa',
                    color: '#333',
                    boxShadow: '0 1px 3px rgba(0,0,0,.1)',
                    wordBreak: 'break-word', // 自动换行
                    overflowWrap: 'break-word',
                    fontSize:'20px'
                  }"
          >
            <div>{{ msg.status }}</div>
            <div>{{ msg.welcome }}</div>
            <div>{{ msg.answer }}</div>
            <el-collapse v-if="msg.status == '检索完成' && screenWidth > 500"
                         v-model="activeNames"
                         style="margin-top: 10px"
                         @change="handleChange">
              <div style="margin-top: 10px;font-size: 20px">{{ msg.title }}</div>

              <el-collapse-item v-for="(item ,index) in msg.content" :title="' 信息来源'+(index+1) +':  ' + item.file_name" :name="item.file_name">
                <div style="margin-top: 10px;font-size: 18px">{{item.content}}</div>
                <div style="margin-top: 10px;font-size: 18px">相关性：{{ item.score }}</div>
              </el-collapse-item>
            </el-collapse>

            <van-collapse v-if="msg.status == '检索完成' && screenWidth <= 500" v-model="activeNames">
              <van-collapse-item v-for="(item ,index) in msg.content" :title="' 信息来源'+(index+1) +':  ' + item.file_name" :name="item.file_name">
                <div style="margin-top: 10px;font-size: 18px">{{item.content}}</div>
                <div style="margin-top: 10px;font-size: 18px">相关性：{{ item.score }}</div>
              </van-collapse-item>

            </van-collapse>
          </div>
        </div>
      </div>

      <!-- 底部输入框 -->
      <div style="display: flex; align-items: center; padding: 10px 16px 30px 16px">
        <el-input
          v-model="userInput"
          placeholder="请输入问题..."
          type="textarea"
          :rows="4"
          @keyup.enter.native="sendMessage"
        ></el-input>
        <el-button
          type="primary"
          icon="el-icon-s-promotion"
          style="margin-left: 8px; background-color: #7363e9"
          @click="sendMessage"
        /></div>
    </div>
  </div>
</template>

<script>
import { robotDetail,botChat } from '@/api/robot/index'
import { getCache } from '@/api/cache/index'

export default {
  components: {  },
  data() {
    return {
      botId:'',
      robotDetail:[],
      chatHistory: [{ role: "bot", welcome: '您好，我是您的专属机器人，请问有什么可以帮您呢？',status:'' }],
      userInput:'',
      activeNames: [],
      screenWidth:0,
      chatSettingConfigured:[
        {
          active:false,
          apiBase:"",
          apiContextLength:4096,
          apiKey: "",
          apiModelName:"",
          capabilities: {networkSearch: false, mixedSearch: false, onlySearch: false, rerank: false},
          chunkSize: 800,
          context: 0,
          maxToken: 512,
          modelType: "openAI",
          temperature: 0.5,
          top_K: 30,
          top_P: 1,
        },
        {
          active:false,
          apiBase:"",
          apiContextLength:4096,
          apiKey: "",
          apiModelName:"",
          capabilities: {networkSearch: false, mixedSearch: false, onlySearch: false, rerank: false},
          chunkSize: 800,
          context: 0,
          maxToken: 512,
          modelType: "ollama",
          temperature: 0.5,
          top_K: 30,
          top_P: 1,
        },
        {
          active:false,
          apiBase:"",
          apiContextLength:4096,
          apiKey: "",
          apiModelName:"",
          capabilities: {networkSearch: false, mixedSearch: false, onlySearch: false, rerank: false},
          chunkSize: 800,
          context: 0,
          maxToken: 512,
          modelType: "自定义模型配置",
          temperature: 0.5,
          top_K: 30,
          top_P: 1,
        }
      ],
    }
  },
  created() {
  },
  mounted() {
    this.screenWidth = window.screen.width;
    this.botId = this.$route.query.botId
    this.getRobotDetail()
  },
  methods: {
    getRobotDetail(){
      robotDetail({bot_id:this.botId}).then(res => {
        this.robotDetail = res.data
      })
    },
    sendMessage() {
      if (!this.userInput.trim()) return;

      this.chatHistory.push({ role: "user", content: this.userInput.trim() });
      this.loading = true;
      if(this.robotDetail.cache){
        getCache({bot_id:this.botId,question:this.userInput.trim()}).then(res => {
          this.chatHistory.push({
            role: "bot",
            answer: res.data.data.matched_question,
          });
        }).catch((error) => {
          this.chat()
        }).finally(() => {
          this.loading = false;
          this.userInput = "";
        })
      }else{
        this.chat()
      }
    },
    chat(){
      //从本地缓存中读取模型配置
      var useChatSetting = []
      if(localStorage.getItem("useChatSetting")){
        useChatSetting = JSON.parse(localStorage.getItem("useChatSetting"))
      }else{
        useChatSetting = this.chatSettingConfigured
      }
      var chatSetting = []
      useChatSetting.forEach(row => {
        if (row.modelType === 'openAI') {
          chatSetting = Object.assign({}, row);
        }
      })
      let param = {
        api_base: chatSetting.apiBase,
        api_context_length: chatSetting.apiContextLength,
        api_key: chatSetting.apiKey,
        bot_id: this.botId,
        chunk_size: chatSetting.chunkSize,
        history: [],
        hybrid_search: chatSetting.capabilities.mixedSearch,
        max_token: chatSetting.maxToken,
        model: chatSetting.apiModelName,
        networking: chatSetting.capabilities.networkSearch,
        only_need_search_results: chatSetting.capabilities.onlySearch,
        product_source: "saas",
        question: this.userInput.trim(),
        rerank: chatSetting.capabilities.rerank,
        streaming: false,
        temperature: chatSetting.temperature,
        top_k: chatSetting.top_K,
        top_p: chatSetting.top_P,
      }

      botChat(param).then(res => {
        var data = JSON.parse(res.substring(5)).source_documents
        this.chatHistory.push({
          role: "bot",
          status: '检索完成',
          title: "找到了"+data.length +'个信息来源：',
          content: data,
        });
        this.$nextTick(() => {
          const box = this.$refs.chatBox;
          box.scrollTop = box.scrollHeight;
        });
      }).finally(() => {
        this.loading = false;
        this.userInput = "";
      })
    },
    handleChange(val) {
    },
  }
}
</script>

<style lang='scss' scoped>
.chat-header{
  width: 100%;
  padding: 5px 0px 5px 0px;
  font-size: 24px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: white;
  color: #222;
}
</style>
